<!-- 优化后的新闻列表页面 -->
<template>
   <s-layout :bgStyle="{ color: '#fff' }" tabbar="/pages/index/news/list/index" title="新闻咨询">
    <su-sticky bgColor="#fff">
      <su-tabs
        :list="state.category"
		keyName='label'
        :scrollable="state.category.length > 7"

        @change="onTabsChange"
        :current="state.currentTab"
      />
    </su-sticky>

    <!-- 骨架屏 -->
    <skeleton-screen
      v-if="state.isFirstLoad"
      :count="5"
      :showTabs="false"
    />

    <!-- 文章列表 -->
    <view class="news-list" v-else>
      <view
        v-for="(article, index) in state.pagination.list"
        :key="article.id"
        class="news-item"
        @click="goToDetail(article)"
        :style="{ animationDelay: `${index * 0.1}s` }"
      >
        <!-- 封面图 -->
        <view class="news-cover" v-if="article.coverImage">
          <image
            :src="article.coverImage"
            mode="aspectFill"
            :lazy-load="true"
            @load="onImageLoad"
            @error="onImageError"
          />
        </view>

        <!-- 文章信息 -->
        <view class="news-info" :class="{ 'no-cover': !article.coverImage }">
          <view class="news-title">{{ article.title }}</view>
          <view class="news-summary">{{ article.summary }}</view>
          <view class="news-meta">
            <text class="news-time">{{ formatTime(article.createTime) }}</text>
            <view class="news-stats" v-if="article.viewCount">
              <text class="stat-item">
                <uni-icons type="eye" size="12" color="#999" />
                {{ formatNumber(article.viewCount) }}
              </text>
              <!-- <text class="stat-item">
                <uni-icons type="heart" size="12" color="#999" />
                {{ formatNumber(article.likeCount) }}
              </text> -->
            </view>
          </view>
        </view>
      </view>
    </view>

    <!-- 空状态 -->
    <empty-state
      v-if="!state.isFirstLoad && state.pagination.list.length === 0"
      type="no-data"
      title="暂无新闻"
      description="当前分类下还没有新闻内容"
      :showButton="true"
      buttonText="刷新"
      @button-click="refreshData"
    />

    <!-- 加载状态 -->
    <uni-load-more
      v-if="state.pagination.list.length > 0"
      :status="state.loadStatus"
      :content-text="loadText"
      @clickLoadMore="loadData"
    />

    <!-- 回到顶部按钮 -->
    <view
      class="back-to-top"
      v-if="state.showBackToTop"
      @click="scrollToTop"
    >
      <uni-icons type="up" size="20" color="#fff" />
    </view>
  </s-layout>
</template>

<script setup>
  import { onLoad, onPullDownRefresh, onReachBottom, onPageScroll } from '@dcloudio/uni-app';
  import { ref, reactive, computed } from 'vue';
  import DictApi from '@/sheep/api/system/dict';
  import NewsApi from '@/sheep/api/news/news';
  import uniIcons from '@dcloudio/uni-ui/lib/uni-icons/uni-icons.vue'
 import { resetPagination } from '@/sheep/helper/utils';
  import { formatDate } from '@/sheep/helper/utils';
  import EmptyState from '@/pages/index/news/components/empty_state_component.vue';
  import SkeletonScreen from '@/pages/index/news/components/skeleton_component.vue'


  const state = reactive({
    category: [],
    currentTab: 0,
    loadStatus: '',
    isFirstLoad: true,
    showBackToTop: false,
    pagination: {
      list: [],
      total: 0,
      pageNo: 1,
      pageSize: 10,
    },
  });

  // 加载状态文本
  const loadText = computed(() => {
    return {
      contentdown: '上拉显示更多',
      contentrefresh: '正在加载...',
      contentnomore: '没有更多数据了'
    };
  });

  // 获取新闻分类集合
  async function getNewsCategoryList() {
    try {
      let { code, data } = await DictApi.getDictDataListByType('category_article');
      if (code !== 0) {
        return;
      }
      if (data && data.length > 0) {
        state.category = [
          { label: '全部', value: '' },
          ...data
        ];
      } else {
        state.category = [{ label: '全部', value: '' }];
      }
    } catch (error) {
      console.error('获取分类失败:', error);
      state.category = [{ label: '全部', value: '' }];
    }

  }

  // 切换选项卡
  function onTabsChange(e) {
    if (state.currentTab === e.index) {
      return;
    }

    // 重新加载数据
    resetPagination(state.pagination);
    state.currentTab = e.index;
    state.isFirstLoad = true;
    getNewsList();
  }

  // 获取新闻列表
  async function getNewsList() {
    if (state.loadStatus === 'loading') return;

    state.loadStatus = 'loading';

    try {
      const category = state.category[state.currentTab]?.value || '';

      let { code, data } = await NewsApi.getNewsPage({
		publishStatus:2,
        pageNo: state.pagination.pageNo,
        pageSize: state.pagination.pageSize,
        category: category,
      });

      if (code !== 0) {
        throw new Error('获取新闻列表失败');
      }

      if (state.pagination.pageNo === 1) {
        state.pagination.list = data.list;
      } else {
        state.pagination.list = state.pagination.list.concat(data.list);
      }

      state.pagination.total = data.total;
      state.loadStatus = state.pagination.list.length < state.pagination.total ? 'more' : 'noMore';

    } catch (error) {
      console.error('获取新闻列表失败:', error);
      state.loadStatus = 'noMore';

      if (state.pagination.pageNo === 1) {
        uni.showToast({
          title: '加载失败，请重试',
          icon: 'error'
        });
      }
    } finally {
      state.isFirstLoad = false;
    }
  }

  // 加载更多数据
  function loadData() {
    if (state.loadStatus === 'loading') return;

    state.pagination.pageNo++;
    getNewsList();
  }

  // 刷新数据
  function refreshData() {
    resetPagination(state.pagination);
    state.isFirstLoad = true;
    getNewsList();
  }

  // 格式化时间
  function formatTime(time) {
    return formatDate(time, 'YYYY-MM-DD HH:mm');
  }

  // 格式化数字
  function formatNumber(num) {
    if (!num) return 0;
    if (num < 1000) return num;
    if (num < 10000) return (num / 1000).toFixed(1) + 'k';
    return (num / 10000).toFixed(1) + 'w';
  }

  // 跳转到详情页
  function goToDetail(article) {
	  console.log(article)
	  if(article.isH5){
		  uni.navigateTo({
		    url: `/pages/index/news/detail/articleUrl?id=${article.id}`
		  });
	  }else{
		  uni.navigateTo({
		    url: `/pages/index/news/detail/index?id=${article.id}`
		  });
	  }

  }

  // 图片加载成功
  function onImageLoad(e) {
    console.log('图片加载成功');
  }

  // 图片加载失败
  function onImageError(e) {
    console.log('图片加载失败');
  }

  // 回到顶部
  function scrollToTop() {
    uni.pageScrollTo({
      scrollTop: 0,
      duration: 300
    });
  }

  // 页面加载
  onLoad((options) => {
    getNewsCategoryList().then(() => {
      getNewsList();
    });
  });

  // 下拉刷新
  onPullDownRefresh(() => {
    refreshData();
    setTimeout(() => {
      uni.stopPullDownRefresh();
    }, 1000);
  });

  // 上拉加载更多
  onReachBottom(() => {
    if (state.loadStatus === 'more') {
      loadData();
    }
  });

  // 页面滚动
  onPageScroll((e) => {
    state.showBackToTop = e.scrollTop > 500;
  });
</script>

<style lang="scss" scoped>
.news-list {
  padding: 20rpx;
}

.news-item {
  display: flex;
  background: #fff;
  border-radius: 16rpx;
  margin-bottom: 20rpx;
  padding: 20rpx;
  box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.1);
  transition: all 0.3s ease;
  opacity: 0;
  animation: fadeInUp 0.6s ease forwards;

  &:active {
    transform: scale(0.98);
    opacity: 0.8;
  }
}

@keyframes fadeInUp {
  from {
    opacity: 0;
    transform: translateY(30rpx);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

.news-cover {
  width: 200rpx;
  height: 140rpx;
  border-radius: 12rpx;
  overflow: hidden;
  margin-right: 20rpx;
  flex-shrink: 0;
  background: #f5f5f5;

  image {
    width: 100%;
    height: 100%;
    transition: transform 0.3s ease;
  }
}

.news-info {
  flex: 1;
  display: flex;
  flex-direction: column;
  justify-content: space-between;

  &.no-cover {
    margin-left: 0;
  }
}

.news-title {
  font-size: 32rpx;
  font-weight: 600;
  color: #333;
  line-height: 1.4;
  margin-bottom: 16rpx;
  display: -webkit-box;
  -webkit-box-orient: vertical;
  -webkit-line-clamp: 2;
  overflow: hidden;
}

.news-summary {
  font-size: 28rpx;
  color: #666;
  line-height: 1.5;
  margin-bottom: 16rpx;
  display: -webkit-box;
  -webkit-box-orient: vertical;
  -webkit-line-clamp: 2;
  overflow: hidden;
}

.news-meta {
  display: flex;
  align-items: center;
  justify-content: space-between;
}

.news-time {
  font-size: 24rpx;
  color: #999;
}

.news-stats {
  display: flex;
  gap: 20rpx;
}

.stat-item {
  display: flex;
  align-items: center;
  gap: 4rpx;
  font-size: 24rpx;
  color: #999;
}

.back-to-top {
  position: fixed;
  right: 30rpx;
  bottom: 160rpx;
  width: 80rpx;
  height: 80rpx;
  background: rgba(0, 122, 255, 0.8);
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  backdrop-filter: blur(10rpx);
  z-index: 999;
  transition: all 0.3s ease;

  &:active {
    transform: scale(0.9);
  }
}

/* 分类标签样式 */
:deep(.su-tabs) {
  .su-tabs-item {
    font-size: 28rpx;
    padding: 20rpx 30rpx;
    transition: all 0.3s ease;

    &.active {
      color: #007aff;
      font-weight: 600;
      transform: scale(1.05);
    }
  }
}

/* 加载更多样式 */
:deep(.uni-load-more) {
  padding: 30rpx 0;
}
</style>

